import {
	createStore
} from 'vuex'
let lifeData = {};

try {
	// 尝试获取本地是否存在lifeData变量，第一次启动APP时是不存在的
	lifeData = uni.getStorageSync('lifeData');
} catch (e) {

}
// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = ['vuex_token'];

// 保存变量到本地存储中
const saveLifeData = function(key, value) {
	// 判断变量名是否在需要存储的数组中
	if (saveStateKeys.indexOf(key) != -1) {
		// 获取本地存储的lifeData对象，将变量添加到对象中
		let tmp = uni.getStorageSync('lifeData');
		// 第一次打开APP，不存在lifeData变量，故放一个{}空对象
		tmp = tmp ? tmp : {};
		tmp[key] = value;
		// 执行这一步后，所有需要存储的变量，都挂载在本地的lifeData对象中
		uni.setStorageSync('lifeData', tmp);
	}
}
const store = createStore({
	// 为了不和页面或组件的data中的造成混淆，state中的变量前面建议加上$符号
	state: {
		vuex_token: lifeData.vuex_token ? lifeData.vuex_token : '',
		//当前登录者用户id
		vuex_user_id: '',
		vuex_user_name: '',
		vuex_user_avatar: '',
		vuex_user_phone: '',
		vuex_user_hide_phone: '',
		vuex_user_sex: 0,
		vuex_user_user_type: '',
		vuex_user_addr: '',
		vuex_user_birth: '',
		vuex_user_today_money: '',
		vuex_user_yes_money: '',
		lat: 0.3,
		response:0,
		StateVh:0,
		screen:0,
		safeArea:0,
		Platform:'',
		shop_data:{},
		share_id:'',
		use_switch:true,
		acieuploa:'https://youlefang.szhulian.cn/api/upload/upload',
		addrs_show:false,
		addrs_data:{},
		addrs_renew:false,
		card_show:false,
		vuex_oid:'',
		vuex_Product:{},
		evalua_data:{},
		after_data:{},
		logistics_list:[],
		evaluate_switch:false
	},
	mutations: {
		GetSteatvh(state) {
			let systemInfo = uni.getSystemInfoSync()
			state.screen = systemInfo.screenHeight	
			state.StateVh = systemInfo.statusBarHeight ||0
			state.safeArea = systemInfo.safeAreaInsets.bottom
			state.response = state.StateVh + 44
			state.Platform = systemInfo.uniPlatform
		},
		//修改头像更新视图
		upludesrc(state, src) {
			state.vuex_user_avatar = src
		},
		//刷新获取用户信息
		usfomData(state, data) {
			state.vuex_user_name = data.nickname
		},
		//持久化存储存取用户id
		luogeStore(state, id) {
			uni.setStorageSync('vuex_user_id', id);
		},
		//处理登录跳转事件状态
		lgoinstus(state) {
			state.loginstus = false
		},
		$uStore(state, payload) {
			// 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
			let nameArr = payload.name.split('.');
			let saveKey = '';
			let len = nameArr.length;
			if (len >= 2) {
				let obj = state[nameArr[0]];
				for (let i = 1; i < len - 1; i++) {
					obj = obj[nameArr[i]];
				}
				obj[nameArr[len - 1]] = payload.value;
				saveKey = nameArr[0];
			} else {
				// 单层级变量，在state就是一个普通变量的情况
				state[payload.name] = payload.value;
				saveKey = payload.name;
			}
			// 保存变量到本地，见顶部函数定义
			saveLifeData(saveKey, state[saveKey])
		},
		//处理登录
		handleLogin(state, payload = {}) {
			//永久 缓存数据
			if(payload.token||payload.type == 'quit'){
				this.commit('$uStore', {
					name: 'vuex_token',
					value: payload.token || ''
				})
			}
			this.commit('luogeStore', payload.id)
			//更新状态
			state.vuex_user_name = payload.name || ''
			state.vuex_user_phone = payload.user_phone || ''
			state.vuex_user_avatar = payload.avatar || ''
			// state.vuex_user_sex = payload.user_sex || ''
			state.vuex_user_id = payload.user_id || ''
			// state.vuex_user_user_type = payload.user_type || ''
		},
	},
	getters: {
		scroll_vh(state){
			return state.screen - (50+state.safeArea) + 'px'
		},
		tabbar_h(state){
			return (state.safeArea + 53)
		}
	},
	actions: {
		//个人信息
		upludeusfmo({
			state,
			commit
		}) {
			if(state.use_switch&&state.vuex_token){
				uni.$u.http.get("/api/user/data").then(res => {
					const data = res.data
					commit('handleLogin',data)
				}).catch(v => {}).finally(()=>{
					state.use_switch= false
				})
			}
		},
		tokenFlushUserInfo({
			state,
			commit
		}) {
			uni.$network('/api/index/website','get').then(res=>{
				const {data} = res
				state.shop_data = data
			})
			if (state.vuex_token) {
				uni.$u.http.post("/api/user/flush", {
					user_token: state.vuex_token
				}).then(({
					data
				}) => {
					commit('handleLogin', data)
				})
			}

		},
		handleLogout({
			state,
			commit
		}) {
			//提交退出信息
			commit('handleLogin', {})
		},
		getSysLocation({
			state,
			commit
		}) {
			if (state.vuex_sys_location_list.length > 0) {
				return
			}
			Vue.prototype.$u.http.post("/api/location/sysLists", {}).then(({
				data
			}) => {
				state.vuex_sys_location_list = data.list || []
				state.vuex_sys_location_hot_list = data.hot_list || []
			})
		},
		bindAppLocation({
			state,
			commit
		}, payload) {
			state.vuex_app_city = payload.city || ""
		},

		//微信登录
		handleWechatLogin({
			state,
			commit
		}) {
			console.log('----------handleWechatLogin')
			uni.login({
				provider: 'weixin',
				success: (loginRes) => {
					console.log(loginRes)
					let data = loginRes
					data['provider'] = 'min_wx'

					//验证登录信息
					Vue.prototype.$u.http.post('/api/index/codeToSession', data)
						.then(({
							code,
							msg,
							data
						}) => {
							//成功
							state.vuex_third_auth_login_data = data || {}
						})
				}
			});
		}

	}
})

export default store
